/**
 * 
 */
package com.wubo.sec.web.action;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.wubo.common.util.StringUtils;
import com.wubo.sec.SecurityManager;
import com.wubo.sec.core.UserData;
import com.wubo.sec.model.Authority;
import com.wubo.sec.model.Menu;
import com.wubo.sec.service.IMenuService;

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;

/**
 * @author WuBo
 * @CreateDate 2010-8-6
 * @UpdateDate 2012-2-27
 * @version 2.0.1
 */
@Controller
public class MenuMgtAction extends BaseSecAction {
	@Autowired
	private IMenuService menuService;
	
	private Set<Menu> menuTree;
	
	private List<Menu> menus;
	
	private Menu menu;
	
	private String id;

	private Set<Menu> userMenuTree;
	
	private String menuname;
	
	private String orderby;
	
	private String locked;
	
	private String leaf;
	
	private String active;

	public String getLeaf() {
		return leaf;
	}

	public void setLeaf(String leaf) {
		this.leaf = leaf;
	}

	public String getLocked() {
		return locked;
	}

	public void setLocked(String locked) {
		this.locked = locked;
	}

	public String getActive() {
		return active;
	}

	public void setActive(String active) {
		this.active = active;
	}

	public IMenuService getMenuService() {
		return menuService;
	}

	public void setMenuService(IMenuService menuService) {
		this.menuService = menuService;
	}

	public Set<Menu> getMenuTree() {
		return menuTree;
	}

	public void setMenuTree(Set<Menu> menuTree) {
		this.menuTree = menuTree;
	}

	public void setMenus(List<Menu> menus) {
		this.menus = menus;
	}
	
	public List<Menu> getMenus() {
		return menus;
	}

	public Menu getMenu() {
		return menu;
	}

	public void setMenu(Menu menu) {
		this.menu = menu;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}
	
	public String getMenuname() {
		return menuname;
	}

	public void setMenuname(String menuname) {
		this.menuname = menuname;
	}

	public String getOrderby() {
		return orderby;
	}

	public void setOrderby(String orderby) {
		this.orderby = orderby;
	}

	public Set<Menu> getUserMenuTree() {
		return userMenuTree;
	}

	public void setUserMenuTree(Set<Menu> userMenuTree) {
		this.userMenuTree = userMenuTree;
	}
	
	private String q; //用于AutoComplete
	public String getQ() {
		return q;
	}
	public void setQ(String q) {
		this.q = q;
	}
	public void autoComplete() {
		try{
			List<String> usernames = menuService.listName(q);
			json(new JSONSerializer().serialize(usernames));
		}catch(Throwable t){
			logger.error(t.getMessage(), t);
			jsonError(null);
		}
	}

	public String list(){
		String where = " where 1=1";
		if(StringUtils.hasText(menuname)){
			where = " where m.name like '%"+menuname+"%'";
		}
		//锁定状态
		if(!(StringUtils.isEmpty(locked))){
			if(!(locked.trim().equals("2"))){
				where += " and locked ="+locked;
			}
		}
		//是否为叶子
		if(!(StringUtils.isEmpty(leaf))){
			if(!(leaf.trim().equals("2"))){
				where += " and leaf ="+leaf;
			}
		}
		//是否启用
		if(!(StringUtils.isEmpty(active))){
			if(!(active.trim().equals("2"))){
				where += " and active ="+active;
			}
		}
		if(StringUtils.isEmpty(orderby)){
			orderby = " order by m.name";
		}

		total = menuService.getTotal(where);
		
		where += orderby;
		
		menus = menuService.getSplitPage(start, limit, where);
		
		menuTree = menuService.findAllTree(false);
		
		super.setUserAttributesToRequest();
		
		return SUCCESS;
	}
	
	public String listOfUser(){
		UserData user = SecurityManager.getCurrentUser();
		
		if(SecurityManager.isAdmin() || SecurityManager.hasAdminAuth(user)){
			userMenuTree = menuService.findAllTree(true);
		}else{
			if(user != null){
				Set<Authority> authorities = user.getAllAuthorities();
				userMenuTree = menuService.getMenuTree(authorities.toArray(new Authority[authorities.size()]));
			}else{
				userMenuTree = menuService.getMenuTree(new Authority[]{Authority.ANONYM_AUTH});
			}
		}
		
		String json = new JSONSerializer().exclude("*.auth").deepSerialize(userMenuTree);
		jsonSuccess(json, true);
		return null;
	}
	
	public void updateTreeStruct(){
		try{
			String originParentCode = ServletActionContext.getRequest().getParameter("originParentCode");
			String newParentCode = ServletActionContext.getRequest().getParameter("newParentCode");
			String nodeIndex = ServletActionContext.getRequest().getParameter("nodeIndex");
			
			menuService.updateStruct(id, originParentCode, newParentCode, Integer.parseInt(nodeIndex));
			
			jsonSuccess(null);
			
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
	}
	
	public void saveTreeStruct(){
		try{
			String trees = ServletActionContext.getRequest().getParameter("trees");
			List<Map<String,?>> menus = new JSONDeserializer<List<Map<String,?>>>().deserialize(trees);
			
			menuService.saveStruct(menus);
			
			jsonSuccess(null);
			
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
	}
	
	public String listForAssign(){
		menuTree = menuService.findAllTreeRunAs();
		
		String result = ServletActionContext.getRequest().getParameter("result");
		if(StringUtils.hasText(result)){
			return result;
		}
		
		return "radio";
	}
	
	public String add(){
		try{
			if(! StringUtils.hasText(menu.getParentCode()) ){
				menu.setParentCode(null);
			}
			menuService.create(menu);
			
			jsonSuccess(null);
			
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
		return null;
	}
	
	public String edit(){
		try{
			if(! StringUtils.hasText(menu.getParentCode()) ){
				menu.setParentCode(null);
			}
			menuService.update(menu);
			
			jsonSuccess(null);
			
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
		return null;
	}

	public String del(){
		menuService.delete(menuService.get(id));
		
		list();
		
		flag = true;
		
		return SUCCESS;
	}
	
	public String dels(){
		try{
			if(StringUtils.hasText(id)){
				menuService.delete(id.split(","));
			}
			
			jsonSuccess(null);
			
		}catch(RuntimeException t){
			jsonError(null);
			throw t;
		}
		return null;
	}
}
